package com.utaedang.jesseclub;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.utaedang.jesseclub.utils.Function;
import com.utaedang.jesseclub.utils.GlobalContext;

public class Downloader extends Activity implements OnClickListener {
	// constants
	private static final int DOWNLOAD_BUFFER_SIZE = 4096;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

	private ProgressBar fileCntProgressBar, fileSizeProgressBar;
	private TextView txt_file_count, txt_file_size;
	private ImageButton ibtn_cancel;
	private Button btn_cancel;
	private Activity activity;

	private ArrayList<String> fileNameList, filePathList;
	// private String homeDir = "";
	private AsyncTask<String, Integer, Long> downloadFileAsyncTask = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.downloader_dialog);
		activity = this;
		
		Intent intent = getIntent();
		ArrayList<String> fpl = new ArrayList<String>();
		ArrayList<String> fnl = new ArrayList<String>();
		
		fpl.add("http://utaedang-db.googlecode.com/files/test.zip");
		//fpl.add("http://utaedang-db.googlecode.com/files/test.zip");
		fnl.add("test01.zip");
		//fnl.add("test02.zip");
		
		intent.putStringArrayListExtra("fileNameList", fnl);
		intent.putStringArrayListExtra("filePathList", fpl);

		fileNameList = intent.getStringArrayListExtra("fileNameList");
		filePathList = intent.getStringArrayListExtra("filePathList");

		fileCntProgressBar = (ProgressBar) findViewById(R.id.file_count_progressbar);
		fileSizeProgressBar = (ProgressBar) findViewById(R.id.file_size_progressbar);
		txt_file_count = (TextView) findViewById(R.id.txt_file_count);
		txt_file_size = (TextView) findViewById(R.id.txt_file_size);
		fileCntProgressBar.setMax(fileNameList.size());
		btn_cancel = (Button) findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(this);

		downloadFileAsyncTask = new DownloadFileAsyncTask().execute();

	}

	public void checkFinishDown(boolean isCanceled) {
		if (isCanceled) {
			Toast.makeText(this, "다운로드가 취소 되었습니다.", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "다운로드가 완료 되었습니다.", Toast.LENGTH_SHORT).show();
			/*
			 * 후작업 필요 시 처리
			 */
			/*
			File targetDir = new File(GlobalContext.DB_PATH);
	        File targetFile = new File(GlobalContext.DB_PATH + "files/" + fileName);
	        Function.unzip(targetFile, targetDir);
	        */
		}
		startActivity(new Intent(this, JesseclubActivity.class));
		activity.finish();
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Log.d("download", "back button click");
			downloadFileAsyncTask.cancel(false);
			requestKillProcess(this);
		}
		return false;
	}

	public void requestKillProcess(final Context context) {

		int sdkVersion = Integer.parseInt(Build.VERSION.SDK);

		if (sdkVersion < 8) {
			ActivityManager am = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			am.restartPackage(getPackageName());
		} else {
			new Thread(new Runnable() {
				public void run() {
					ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
					String name = getApplicationInfo().processName;

					while (true) {
						List<RunningAppProcessInfo> list = am
								.getRunningAppProcesses();

						for (RunningAppProcessInfo i : list) {
							if (i.processName.equals(name) == true) {

								if (i.importance >= RunningAppProcessInfo.IMPORTANCE_BACKGROUND)
									am.restartPackage(getPackageName());

								Thread.yield();
								break;
							}
						}
					}
				}

			}, "Process Killer").start();
		}
	}
	
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_cancel: // 취소
			downloadFileAsyncTask.cancel(false);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	/*
	 * Activity에 투명도 주기
	 */
	/*
	@Override
	protected void onApplyThemeResource(Resources.Theme theme, int resid,
			boolean first) {
		super.onApplyThemeResource(theme, resid, first);

		// no background panel is shown
		theme.applyStyle(android.R.style.Theme_Panel, true);
	}
	*/

	private class DownloadFileAsyncTask extends
			AsyncTask<String, Integer, Long> {

		boolean isCanceled = false;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}

		@Override
		protected Long doInBackground(String... strData) {
			try {
				for (int i = 0; i < fileNameList.size() && !isCanceled; i++) {
					URL url = new URL(filePathList.get(i));
					URLConnection conn = url.openConnection();
					conn.setUseCaches(false);
					int fileSize = conn.getContentLength();
					long lastModified = conn.getLastModified();

					String fileName = fileNameList.get(i);

					int fileSizeInKB = fileSize / 1024;
					Log.v("download",
							getString(R.string.progress_dialog_title_downloading));
					// start download
					BufferedInputStream inStream = new BufferedInputStream(
							conn.getInputStream());
					// app 내부에 쓰기
					String dirName = GlobalContext.DB_PATH + "files";
					File targetdir = new File(dirName);
					if (!targetdir.isDirectory()) {
						targetdir.mkdirs();
					}
					File outFile = new File(GlobalContext.DB_PATH + "files/"
							+ fileName);
					if (outFile.exists()) {
						outFile.delete();
						outFile.createNewFile();
					}

					FileOutputStream fileStream = new FileOutputStream(outFile);
					BufferedOutputStream outStream = new BufferedOutputStream(
							fileStream, DOWNLOAD_BUFFER_SIZE);
					byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
					int bytesRead = 0, totalRead = 0;
					while (!isCanceled
							&& (bytesRead = inStream.read(data, 0, data.length)) >= 0) {
						outStream.write(data, 0, bytesRead);

						// update progress bar
						totalRead += bytesRead;
						int totalReadInKB = totalRead / 1024;
						// publishProgress(totalReadInKB);
						// publishProgress((int)((totalRead*100)/fileSizeInKB),
						// i);
						publishProgress(
								(int) ((totalReadInKB * 100) / fileSizeInKB), i);

					}
					// callback onProgressUpdate
					publishProgress(0, i + 1);

					outStream.close();
					fileStream.close();
					inStream.close();

					if (isCanceled) {
						outFile.delete();
					} else {
						Log.v("test", "다운로드 완료");
					}
				}
			} catch (MalformedURLException e) {
				Log.d("download", "MalformedURLException");
			} catch (FileNotFoundException e) {
				Log.d("download", "FileNotFoundException");
			} catch (Exception e) {
				Log.d("download", "에러 Exception");
			} finally {

			}
			return null;
		}

		@Override
		protected void onCancelled() {
			isCanceled = true;
			checkFinishDown(isCanceled);
			activity.finish();
			super.onCancelled();
		}

		// publishProgress(…) 메소드 호출의 callback
		@Override
		protected void onProgressUpdate(Integer... progress) {

			fileSizeProgressBar.setProgress(progress[0]);
			fileCntProgressBar.setProgress(progress[1]);
			txt_file_count.setText("다운로드 완료 : " + progress[1] + " / "
					+ fileNameList.size());
			txt_file_size.setText("진행상태 : " + progress[0] + "%");
		}

		@Override
		protected void onPostExecute(Long unused) {
			checkFinishDown(isCanceled);
			activity.finish();
		}
	}
}